<?php

namespace app\order\logic;

use think\facade\Db;
use app\data\util\HttpUtil;

class ReamazeLogic
{
    
    public function CheckTask()
    {
        //删除标签
        $task = Db::name('customer_email_del')->where('status',0)->find();
        if(empty($task)){
            echo PHP_EOL."没有需要删除的标签". PHP_EOL;
        }else{
            echo PHP_EOL."开始删除".$task['tag']."标签". PHP_EOL;
            $this->DeleteATap($task['tag']);die;
            //删除之后更新状态
            // $this->Apireamaze($CreatedAt);die;
        }

        //邮件任务
        $task = Db::name('customer_email_log')->where('status',0)->find();
        if(empty($task)){
            echo PHP_EOL."没有需要发送邮件的客户". PHP_EOL;
        }else{
            echo PHP_EOL."有需要发送邮件的客户". PHP_EOL;
            //发送消息
            $this->SendMessage($task);die; 
        }

        //新增标签
        $task = Db::name('customer_email_add')->where('status',0)->find();
        if(empty($task)){
            echo PHP_EOL."没有需要新增的标签". PHP_EOL;
        }else{
            echo PHP_EOL."有需要新增的标签". PHP_EOL;
            //新增标签
            (new ReamazeLogic())->ModifyTags($task);
            $this->ModifyTags($task);die;
        }
    }

    /**
    * @desc    发送消息
    * @author  zhangheng
    */
    public function SendMessage($task)
    {
        $source_id = $task['source_id'] ?? 0;
        $shop_id = $task['shop_id'] ?? 0;
        if($source_id == 0){
            echo "ID为空". PHP_EOL;
            return false;
        }
        switch ($shop_id) {
            case '17':
                $shop_id = 'SheCurve';
                break;
            case '18':
                $shop_id = 'LilyLove';
                break;
            case '21':
                $shop_id = '4304ef';
                break;
            default:
                $shop_id = 0;
        }
        if($shop_id == 0){
            echo "店铺未找到". PHP_EOL;
            return false;
        }

        $config = Db::name('customer_email_config')->where('id',$source_id)->find();
        $date_zone_start = $config['date_zone_start'] ?? '';
        $date_zone_end = $config['date_zone_end'] ?? '';
        $message = $config['message'] ?? '';
        if(empty($date_zone_start) || empty($date_zone_end) || empty($message)){
            echo "缺少时间区间或者消息模板参数". PHP_EOL;
            return false;
        }
        $t1       = microtime(true);
        $count = $list = Db::name('conversations')
            ->where('update_type',0)
            ->where('status',0)
            ->where('channel',1)
            ->where('brand',$shop_id)
            ->where('created_at',">=",$date_zone_start)
            ->where('created_at',"<=",$date_zone_end)
            ->count();
        echo "总计:" . $count . '条' . PHP_EOL;
        if($count == 0){
            echo "没有需要发送邮件的客户". PHP_EOL;
            return false;
        }
        $pageSize = 600;
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 0; $i < $page; $i++){
            $list = Db::name('conversations')
                ->where('update_type',0)
                ->where('status',0)
                ->where('channel',1)
                ->where('brand',$shop_id)
                ->where('created_at',">=",$date_zone_start)
                ->where('created_at',"<=",$date_zone_end)
                ->order('created_at asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
            foreach ($list as $v){
                //修改标签
                $return_con = $this->SendMessageinfo($v,$message);
                if($return_con){
                    $executedCountsu++;
                    $update['update_type'] = 1;
                }else{
                    $update['update_type'] = 2;
                }
                Db::name('conversations')->where('id',$v['id'])->update($update);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前ID'.$v['id'].$v['slug'].',第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    public function SendMessageinfo($v,$message)
    {
        $brand = $v['brand'] ?? 'SheCurve';
        $slug = $v['slug'];
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        //邮箱搜索
        $url = 'https://'.$brand.'.reamaze.io/api/v1/conversations/'.$slug.'/messages';
        $data['message']['body'] = $message;
        $data['message']['visibility'] = 0;
        $data['message']['suppress_autoresolve'] = true;
        $data['message']['suppress_notifications'] = false;
        HttpUtil::postUrlReamaze($url,$data, ['email' => $email, 'token' => $token]);
        $this->ModifyTagsinfo($v,"replay");

        return true;
    }
    
    public function Apireamaze($CreatedAt)
    {
        halt($CreatedAt);
        $brands = [
            0 => 'SheCurve',
            1 => '4304ef',
            2 => 'LilyLove',
        ];
        foreach($brands as $key => $val){
            $this->Apireamazeinfo($val);
        }
    }

    public function Apireamazeinfo($brand)
    {
        echo $brand."新增消息会话" . PHP_EOL;
        // $page = 31342;
        for ($i = 1; $i <= 10; $i++){
            $this->Apireamazes($i,$brand);
            echo $i . "完成" . PHP_EOL;
        }
    }
    
    public function Apireamazes($page,$brand = 'SheCurve')
    {
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        // 消息列表
        $url = 'https://'.$brand.'.reamaze.io/api/v1/conversations?page='.$page.'&filter=all&sort=updated_at';
        $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
        halt($return['page_count']);
        if(isset($return['conversations']) && !empty($return['conversations'])){
            $conversations = $return['conversations'];
            $count = 0;
            foreach($conversations as $key => $val){
                $count++;
                if($val['category']['channel'] !== 1){
                    continue;
                }
                $slug = Db::name('conversations')->where(['slug' => $val['slug']])->find();
                if($slug){
                    $update = [
                        'status'              => $val['status'] ?? "",
                        'tag_list'          => json_encode($val['tag_list'],true) ?? "",
                        'created_at'        => $val['created_at'],
                        'updated_at'        => $val['updated_at'],
                        'channel'        => $val['category']['channel'] ?? "",
                        'brand'        => $brand,
                        // 'email'        => $val['category']['email'] ?? "",
                    ];
                    echo $brand."修改".$update['created_at']."---".$val['slug']."---".$val['status']. PHP_EOL;
                    try {
                        Db::name('conversations')->where(['slug' => $val['slug']])->update($update);
                    } catch (\Throwable $e) {
                        echo "修改失败". PHP_EOL;  
                        continue;
                    }
                }else{
                    $insert = [
                        'subject'           => $this->removeNonAscii($val['subject']),
                        'slug'              => $val['slug'],
                        'tag_list'          => json_encode($val['tag_list'],true) ?? "",
                        'status'            => $val['status'] ?? "",
                        'author'            => $this->removeNonAscii($val['author']['name']),
                        'message_count'     => $val['message_count'],
                        'created_at'        => $val['created_at'],
                        'updated_at'        => $val['updated_at'],
                        'channel'        => $val['category']['channel'] ?? "",
                        // 'email'        => $val['category']['email'] ?? "",
                        'json'              => $this->removeNonAscii(json_encode($val,true)),
                        'brand'        => $brand,
                    ];
                    echo $brand."新增".$insert['created_at']."---".$insert['slug']. PHP_EOL;
                    try {
                        Db::name('conversations')->insert($insert);
                    } catch (\Throwable $e) {
                        echo "新增失败". PHP_EOL;  
                        continue;
                    }
                }
            }
        }
        return true;
    }

    public function removeNonAscii($string) {  
        $output = '';  
        for ($i = 0; $i < mb_strlen($string, 'UTF-8'); $i++) {  
            $char = mb_substr($string, $i, 1, 'UTF-8');  
            if (ord($char[0]) < 128) {  
                $output .= $char;  
            }  
        }  
        return $output;  
    } 

    /**
    * @desc    新增标签
    * @author  zhangheng
    */
    public function ModifyTags($task)
    {
        $tag = $task['tag'] ?? '';
        //新增标签
        $tags = [
            0 => "AAAAA",
            1 => "BBBBB",
            2 => "CCCCC",
            3 => "DDDDD",
            4 => "EEEEE",
            5 => "FFFFF",
            6 => "GGGGG",
            7 => "HHHHH",
            8 => "JJJJJ",
            9 => "KKKKK",
            10 => "LLLLL",
            11 => "MMMMM",
            12 => "NNNNN",
            13 => "OOOOO",
        ];
        foreach ($tags as $k => $v) {
            $updatec = Db::name('conversations')
                ->where('status',0)
                ->where('tags_type',0)
                ->where('channel',1)
                ->where('tags',$v)
                ->where('created_at',">=","2025-01-15")
                ->update(
                    [
                        'tags_type' => 2,//无需修改标签
                    ]
                );
                echo $v."修改标签".$updatec . PHP_EOL;
        }
        echo '查询完成' . PHP_EOL;

        $date_zone_start = $task['date_zone_start'] ?? '';
        $date_zone_end = $task['date_zone_end'] ?? '';
        if(empty($date_zone_start) || empty($date_zone_end)){
            echo "缺少时间区间参数". PHP_EOL;
            return false;
        }

        $t1       = microtime(true);
        $count = $list = Db::name('conversations')
            ->where('tags_type',0)
            ->where('status',0)
            ->where('channel',1)
            ->where('updated_at',">=",$date_zone_start)
            ->where('updated_at',"<=",$date_zone_end)
            ->count();
        echo "总计:".$count."条". PHP_EOL;
        if($count == 0) return true;
            
        if($tag == "ALL" || $tag == ""){
            $tag_new = $tags;
        }else{
            if(!in_array($tag,$tags)){
                echo $tag."标签不在规则范围内". PHP_EOL;die;
            }
            $tag_new = [$tag];
        }

        $pageSize = 600;
        $page     = count($tag_new);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 0; $i < $page; $i++){
            $list = Db::name('conversations')
                ->where('tags_type',0)
                ->where('status',0)
                ->where('channel',1)
                ->where('updated_at',">=",$date_zone_start)
                ->where('updated_at',"<=",$date_zone_end)
                ->order('created_at asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
            foreach ($list as $v){
                //新增标签
                $return_con = $this->ModifyTagsinfo($v,$tag_new[$i]);
                if($return_con){
                    $executedCountsu++;
                    $update['tags_type'] = 1;
                    $update['tags'] = $tags[$i];
                }else{
                    $update['tags_type'] = 2;
                }
                Db::name('conversations')->where('id',$v['id'])->update($update);

                $executedCount++;
                $num = $count - $executedCount;
                // echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前ID'.$v['id'].$v['created_at'].',第' .$i.'页' . PHP_EOL;
            }
        }
        // echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        return true;
    }
    
    public function ModifyTagsinfo($v,$tags)
    {
        $brand = $v['brand'] ?? 'SheCurve';
        $tags = trim($tags);
        $slug = $v['slug'];
        $tag_list = [$tags];
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        //邮箱搜索
        // halt($tag_list);
        $url = 'https://'.$brand.'.reamaze.io/api/v1/conversations/'.$slug;
        $data['conversation']['tag_list'] = $tag_list;
        HttpUtil::putUrlReamaze($url,$data, ['email' => $email, 'token' => $token]);
        // halt($return);
        return true;
    }

    /**
    * @desc    删除标签
    * @author  zhangheng
    */
    public function DeleteATap($tag)
    {
        $tags = [
            0 => "AAAAA",
            1 => "BBBBB",
            2 => "CCCCC",
            3 => "DDDDD",
            4 => "EEEEE",
            5 => "FFFFF",
            6 => "GGGGG",
            7 => "HHHHH",
            8 => "JJJJJ",
            9 => "KKKKK",
            10 => "LLLLL",
            11 => "MMMMM",
            12 => "NNNNN",
            13 => "OOOOO",
        ];
        if($tag == "ALL" || $tag == ""){
            $tag = $tags;
        }else{
            if(!in_array($tag,$tags)){
                echo $tag."标签不在规则范围内". PHP_EOL;die;
            }
        }
        
        foreach ($tags as $k => $tag) {
            $executedCount = 0;
            $executedCountsu = 0;
            $count = Db::name('conversations')
                ->where('tags',$tag)
                ->count();
            $list = Db::name('conversations')
                ->where('tags',$tag)
                ->order('created_at asc')
                ->select()
                ->toArray();
            foreach ($list as $v){
                //修改标签
                $return_con = $this->DeleteTagsinfo($v);
                if($return_con){
                    $executedCountsu++;
                    $update['tags_type'] = 0;
                    $update['tags'] = "";
                }else{
                    $update['tags_type'] = 2;
                }
                Db::name('conversations')->where('id',$v['id'])->update($update);

                // $executedCount++;
                // $num = $count - $executedCount;
                // echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前ID'.$v['id'].$v['created_at'].',' . PHP_EOL;
            }
        }
        // echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        return true;
    }

    public function DeleteTagsinfo($v)
    {
        $brand = $v['brand'] ?? 'SheCurve';
        $slug = $v['slug'];
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        //邮箱搜索
        $url = 'https://'.$brand.'.reamaze.io/api/v1/conversations/'.$slug;
        $data['conversation']['tag_list'] = [];
        HttpUtil::putUrlReamaze($url,$data, ['email' => $email, 'token' => $token]);
        return true;
    }


}
